<?php
namespace control;
/*
*每周菜谱类
*/

class weekMenuClass extends adIndexClass
{
    private const page = 'weekMenu';
    private const table = 'dining_week_menu';
    private const tableMx = 'dining_week_menu_detail';
    private const title = '每周菜谱';
    public array $weekArray = ['周日','周一','周二','周三','周四','周五','周六'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'hall'          => [
                        'name'  => '食堂名称',
                        'width' => 200,
                    ],
                    'name' => [
                        'name'  => "菜谱名称",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'startDate'  => [
                        'name'  => "起止日期",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'state'         => [
                        'name'  => '状态',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'stid'          => [
                        'name'  => '创建人',
                        'width' => 200,
                    ],
                    'time'          => [
                        'name'  => '创建日期',
                        'width' => 300,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "食堂名称" => selectMultiple(["name" => "hallId", 'table' => "dining_hall", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200']),
                    "菜谱名称"     => text(array("name" => "name")),
                    "开始日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ],
                [
                    "状态" => select(["name" => "state", 'option' => ['启用','停用']]),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .=  "<span onclick=\"newIframe('" . self::title . "编辑','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "name" => $this->post('name'),//食堂名称
        );
        //全等查询数组
        $equal = array(
            "hallId" => $this->post('hallId'),
            "state" => $this->post('state'),//状态
        );
        $and='';
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'),field: 'startDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'updateTime',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)).$and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        $url = root . "control/adIndex.html?cla=" . self::page;
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "hall":
                        $hall = query('dining_hall',"id = '$array[hallId]'");
                        $row[] = $hall['name'];
                        break;
                    case "startDate":
                        $row[] = $array['startDate'].'至'.$array['endDate'];
                        break;
                    case "stid":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /**
     * 启用/停用
     */
    public function stateSwitch(): bool|string
    {
        $type = $this->post('type');
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "提示：" => "是否修改所选数据状态为：" . $type,
            ),
        ), 'hidden' => hidden(array('name' => 'type', 'value' => $type))));
        //返回
        return $this->layer(array("title" => "状态切换", "height" => 165, "html" => $html, 'formTwo' => 'listForm'));
    }

    /**
     * 启用/停用
     */
    public function stateSwitchEdit(): bool|string
    {
        $idArr = $this->post('id') ? [$this->post('id')] : $this->post('listId');
        $state = $this->post('type');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有" . self::title . "的编辑权限";
        } elseif (empty($idArr) || !is_array($idArr)) {
            $json['warn'] = "请选择数据";
        } elseif (!in_array($state, ['启用', '停用'])) {
            $json['warn'] = "类型错误";
        } else {
            $field = [
                'state' => $state,
            ];
            $json['warn'] = update(array('table' => self::table, 'field' => $field, 'where' => " id in ('" . implode("','", $idArr) . "')"));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "的状态为【{$state}】， id：【" . implode(",", $idArr) . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            }
        }
        //返回
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $info = query(self::table, " id = '" . $this->get('id') . "' ");
        $button[] = [
            "name" => "保存",
            "type" => "点击事件",
            "fun" => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
            'style' => 'li-btn-blue-bg',
        ];
        $w = date('w');//当前日期为周几
        $d = $w?$w-1:6;//周日需减6天
        $startDate = $info['id']?$info['startDate']:date('Y-m-d',strtotime("-{$d} day"));
        $endDate = $info['id']?$info['endDate']:date('Y-m-d',strtotime("+6 day",strtotime($startDate)));
        //表单
        $data['button'] = $this->tableShowButton($button);
        $data['html'] = $this->pageEdit([
            "table" => [
                '基本信息' => [
                    [
                        must . "食堂名称：" =>  selectMultiple(["name" => "hallId",'value'=>$info['hallId'], 'table' => "dining_hall", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => '食堂名称']),
                        must . "菜谱名称：" => text(["name" => "name", 'class' => 'text', "value" => $info['name']]),
                        must . "开始日期：" =>text(["name" => "startDate", 'laydate'=>['showBottom'=>false,'done'=>"function(value, date){changeData(date);obtainHtml();}",'ready'=>"function(date) {onlyMonday()}",'change'=>"function() {return onlyMonday()}"],'class' => 'width200', "value" => $startDate]).
                            "<span id='date-span1'>{$startDate}</span>至<span id='date-span2'>{$endDate}</span>",
                    ],
                    [
                        "备注：" => textarea(["name" => "text", "value" => $info['text']]),
                    ],
                    [
                        "<div class='small-title'></div>"
                    ],
                    [
                        "<div id='cookContent'></div>"
                    ],
                ]
            ],
            'hidden' => hidden(['name' => 'id', 'value' => $info['id'] ?: $this->get('id')]),
        ]);
        //返回
        return $this->tab($data).$this->editJs();
    }

    public function editJs(): string
    {
        return <<<eof
        <script>
         //点击空白页弹出选择菜单界面
         $(document).on('click','.orderMenu',function (){
            let id = $(this).find("[name='mxId[]']").val();
           if (!id){
               msg('未找到ID','error')
           }else{
               layer('weekMenu','dining_menu',$(this).find("input").serialize())
           }
         })
        $(document).on('click',".del_text",function(event) {
            $(this).parent().remove();
            event.stopPropagation();//阻止事件冒泡
        })
         function addRow(){
              $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=dining_menuEdit',$("form[name='mxForm']").serialize(),function(res) {
                    if (res.warn ==2){
                         let mealype = '';
                        $('#weekMenuDining_menu').hide();
                        $("[name='mxId[]']").each(function() {
                           mealype =$(this).parent().find("[name='mealClassify[]']").val();
                          if (res.id == $(this).val() && mealype == res.mealType ){
                              $(this).parent().find(".menu_list").append(res.html)
                          }
                        })
                    }else{
                        msg(res.warn,'error')
                    }
                },'json');
         }
         function changeData(date){
             let now = date.year+'-'+date.month+'-'+date.date,
                    end = addDate(now, 6)
                $("#date-span1").html(now)
                $("#date-span2").html(end)
         }
         function addDate (date, days) {
                var d = new Date(date);
                d.setDate(d.getDate() + days);
                var m = d.getMonth() + 1;
                m = m < 10 ? '0' + m : m;
                var dd = d.getDate();
                dd = dd < 10 ? '0' + dd : dd;
                return d.getFullYear() + '-' + m + '-' + dd;
         }
         
         function obtainHtml(){
             let date = $("[name='startDate']").val();
             let id = $("[name='id']").val();
            
             $.post(root+'control/adIndex.html?cla=weekMenu&fun=obtainHtml',{date:date,id:id},function(res) {
                $("#cookContent").empty().append(res.html);
             },'json')
         }
         $(function() {
           obtainHtml();
         })
        </script>
eof;
    }

    /**
     * 获取菜谱
     * @return bool|string
     */
    public function obtainHtml(): bool|string
    {
        $json['html'] = $this->orderMenu($this->post('id'),$this->post('date'));
        return json_encode($json,320);
    }

    /**
     * 选择菜品
     */
    public function dining_menu(): bool|string
    {
        $tdId = $this->post('mxId')[0];
        $mealType =  $this->post('mealClassify')[0];
        $html =
            select(["name" => "menuType", 'option' => explode('，',para('menuType')), 'title' => '分类']).
            text(array("name" => "name", "title" => "菜品名称")) .
            hidden(array('name'=>'tdId','value'=>$tdId)).
            hidden(array('name'=>'mealType','value'=>$mealType)).
            hidden(array('name' => 'materialId', 'value' => $this->post('menuId') ? implode(',', $this->post('menuId')[$mealType][$tdId]) : ''));
        $button = "<input style='margin-left: 5px' onclick=\"addRow()\" type='button' class='searchSub' value='提交'>";
        $html = $this->search($html);
        return $this->layer(array("title" => "添加", "height" => 500, "html" => $html, "button" => $button));
    }

    /**
     *选择菜品
     */
    public function dining_menuSearch(): bool|string
    {
        $materialId = $this->post('materialId') ? explode(',', $this->post('materialId')) : [];
        $where = " 1=1 and id not in ('" . implode("','", $materialId) . "')";
        $like = [
            'name' => $this->post('name'),
        ];
        $equal = [
            'state' => '启用',
            'type' =>$this->post('menuType'),
        ];
        $where .= search(["like" => $like, "=" => $equal]);
        $page = $this->page([
            "table" => "dining_menu",
            "where" => $where,
            'pageNum' => 50,
            "order" => "`time` ASC",
        ]);
        //获取表头
        $checkAll = $this->checkAll("mxForm", "mxId");
        $tr[] = [$checkAll, '分类', '名称'];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "mxId", "value" => $array['id']),
            );
            $tr[] = array(
                $this->dominate($dominate),
                $array['type'],
                $array['name'],
            );
        }
        $json['html'] = $page['hint'] .
            "<form name='mxForm'>" .
                hidden(array('name'=>'tdId','value'=>$this->post('tdId'))).
                hidden(array('name'=>'mealType','value'=>$this->post('mealType'))) .
                $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) .
            "</form>" .
            $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function dining_menuEdit(): bool|string
    {
        $mxIdArr = $this->post('mxId');
        $tdId = $this->post('tdId');
        $mealType = $this->post('mealType');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (static::is_null_array($mxIdArr)) {
            $json['warn'] = '请选择菜品';
        } elseif(empty($tdId)){
            $json['warn'] = '未找到ID';
        } elseif(empty($mealType)){
            $json['warn'] = '未找到餐别';
        }else {
            $json['html'] = '';
            foreach ($mxIdArr as $mxId) {
                $dining_menu = query('dining_menu', "id = '$mxId'");
                $json['html'] .= <<<efo
                 <li><span>{$dining_menu['name']}</span><span class='del_text'>×</span><input name="menuId[$mealType][$tdId][]" value="{$mxId}" type="hidden"></li>
efo;

            }
            $json['id'] = $tdId;
            $json['mealType'] = $mealType;
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

    /**
     * 菜谱
     */
    public function orderMenu($id='',$startDate=null,$isShow=false,$isStatistics = false): string
    {
        $hidden = $isShow?"hidden":'';
        $info = query(self::table,"id = '$id'");
//        $w = date('w');//当前日期为周几
//        $d = $w?$w-1:6;//周日需减6天
        $dateStart = query('dining_week_menu_date',"orderId = '$id' order by orderDate asc");
        $startDate = $dateStart['id']?$dateStart['orderDate']:$startDate;
        $weekTr = "<tr><td></td>";
        for ($i=0;$i<7;$i++){
            $toDate = strtotime("+{$i} day",strtotime($startDate));
            $weekTr.="<td>".$this->weekArray[date('w',$toDate)].date('m-d',$toDate)."</td>";
        }

        $weekTr .= "</tr>";
        $menuTr = '';
        $mealType = explode('，',para('mealOption'));
        foreach ($mealType as $val){
            $menuTr .= "<tr><td>";
            for ($word=0;$word<mb_strlen($val);$word++){
                $menuTr .="<p>".mb_substr($val,$word,1)."</p>";
            }
            $menuTr .= "</td>";
            for ($i=0;$i<7;$i++){
                $orderDate =date('Y-m-d',strtotime("+{$i} day",strtotime($startDate)));
                if (!empty($info['id'])){
                    $toDay = query('dining_week_menu_date',"orderId = '$id' and orderDate = '$orderDate'");
                    $menuTr.="<td class='orderMenu top-text' data-edit='1'><input name='mxId[]' type='hidden' value='$toDay[id]'><input name='mealClassify[]' type='hidden' value='$val'><input name='orderDate[{$val}][{$toDay['id']}]' type='hidden' value='$toDay[orderDate]'><ul class='menu_list'>";
                    $menuAll = find(array('table'=>self::tableMx,'where'=>"orderId = '$id' and mealType = '$val' and localDate = '$toDay[orderDate]'"));
                    foreach ($menuAll['array'] as $menu){
                        $dish = query('dining_menu',"id = '$menu[menuId]'");
                        $numText = '';
                        if ($isStatistics){
                            $num = find(array('table'=>'meal_report as a join meal_report_detail as b on a.id = b.orderId','single'=>"a.recordDate = '$orderDate' and a.hallId = '$info[hallId]' and a.mealType = '$val' and b.menuId = '$dish[id]'",'field'=>"ifnull(sum(b.num),0) as num"))['num'];
                            $numText = $num.'份';
                        }
                        $menuTr.="<li><span>".$dish['name']."&nbsp;".$numText."</span><span class='del_text {$hidden}'>×</span><input name='menuId[{$val}][{$toDay['id']}][]' value='$menu[menuId]' type='hidden'></li>";
                    }
                    $menuTr.="</ul></td>";
                }else{
                    $mxId = self::getId();
                    $menuTr.="<td class='orderMenu' data-edit='1'><input name='mxId[]' type='hidden' value='$mxId'><input name='mealClassify[]' type='hidden' value='$val'><input name='orderDate[{$val}][{$mxId}]' type='hidden' value='$orderDate'><ul class='menu_list'></ul></td>";
                }
            }
            $menuTr .= "</tr>";
        }

        return <<<eof
<div class="$hidden" style="color: #FF9900">*点击空白区域添加菜品</div>
<div class="menu_content">
    <table class="menu_table">
        {$weekTr}
        {$menuTr}
    </table>
</div>
<style>
.top-text{vertical-align: top}
.menu_table{border-collapse: collapse;border-spacing: 0;table-layout: fixed}
.menu_table tr:first-child{font-weight: bold}
.menu_table tr td{border: 1px solid #F2F2F2;min-width: 200px}
.menu_table tr td:first-child{background-color: #F2F2F2;font-weight: bold;width: 40px;}
.menu_table tr td:first-child p{text-align: center;line-height: 80px}
.menu_list>li{min-width: 100px; max-width:177px;background-color: #F2F2F2;padding: 3px 7px;margin: 2px auto}
.del_text{float: right;margin-right: 10px;font-weight: 400;cursor:pointer;font-size: 18px;color: #AAAAAA;font-kerning: normal;}
.del_text:hover{color: red}
.menu_table tr:nth-child(n+2) > td:nth-child(n+2){cursor: pointer}
</style>
eof;

    }

    /**
     * 编辑
     * @return bool|string
     */
    public function editEdit(): bool|string
    {
        $id = $this->post('id') ?: self::getId();
        $mxIdArr = $this->post('mxId');
//        $mealTypeArr = $this->post('mealClassify');
        $orderDateArr = $this->post('orderDate');
        $menuIdArr = $this->post('menuId');
        $field = [
            'hallId' => $this->post('hallId'),
            'startDate' => $this->post('startDate'),
            'name' => $this->post('name'),
            'text' => $this->post('text'),
        ];
        $annotation = [
            'hallId' => '食堂名称',
            'name' => '菜谱名称',
            'startDate' => '菜谱名称',
        ];
        $rules = [
            'hallId' => 'required',
            'name' => 'required',
            'startDate' =>'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif(static::total(array('table'=>self::table,'where'=>"startDate = '$field[startDate]' and hallId = '$field[hallId]' and id !='$id'")) >0){
            $json['warn'] = "此日期已存在此食堂的菜谱";
        }elseif(static::is_null_array($mxIdArr)){
            $json['warn'] = '请添加菜品';
        }else {
            $this->startTrans();
            $field['endDate'] = date('Y-m-d',strtotime("+6 day",strtotime($field['startDate'])));
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $field = array_merge($field, [
                    'id' => $id,
                    'stid' => $this->control['stid'],
                    'state'=>'启用',
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            $dateId = [];
            $detailId = [];
            $mealType = explode('，',para('mealOption'));
            foreach ($mealType as $val){
                foreach ($mxIdArr as $mxId){
                    /***日期********/
                    $today = $orderDateArr[$val][$mxId]??'';
                    if ($today){
                        $week_date = query('dining_week_menu_date',"orderId = '$id' and orderDate = '$today'");
                        if (empty($week_date['id'])){
                            $week_menu_date_id = self::getId();
                            $dateId[] =$week_menu_date_id;
                            $warn = static::insert(array(
                                'table'=>'dining_week_menu_date',
                                'field'=>[
                                    'id'=>$week_menu_date_id,
                                    'orderId'=>$id,
                                    'orderDate'=>$today,
                                    'weekName'=>$this->weekArray[date('w',strtotime($today))],
                                ],
                            ));
                            if (!in_array($warn, ["新增成功", "更新成功"])){
                                $json['warn'] = $warn;
                                break 2;
                            }
                        }else{
                            $dateId[] = $week_date['id'];
                        }
                    }

                    /******菜品*********/
                    if (isset($menuIdArr[$val][$mxId]) && is_array($menuIdArr[$val][$mxId])){
                        foreach ($menuIdArr[$val][$mxId] as $menuId){
                            $mx = query(self::tableMx,"menuId = '$menuId' and localDate = '$today' and mealType = '$val'");
                            if (empty($mx['id'])){
                                $oId = self::getId();
                                $detailId[] = $oId;
                                $warn = static::insert(array(
                                    'table'=>self::tableMx,
                                    'field'=>[
                                        'id'=>$oId,
                                        'orderId'=>$id,
                                        'mealType'=>$val,
                                        'localDate'=>$today,
                                        'menuId'=>$menuId,
                                    ]
                                ));
                                if (!in_array($warn, ["新增成功", "更新成功"])){
                                    $json['warn'] = $warn;
                                    break 2;
                                }
                            }else{
                                $detailId[] = $mx['id'];
                            }
                        }
                    }

                }
            }

            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                delete(array('table' => 'dining_week_menu_date', 'where' => " id not in ('" . implode("','", $dateId) . "') and orderId = '$id'"));
                delete(array('table' => self::tableMx, 'where' => " id not in ('" . implode("','", $detailId) . "') and orderId = '$id'"));
                $this->commitTrans();
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }else{
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }
    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );
            $button = [];
            if ($this->power(self::page, "edit")) {
                //按钮
                $button[] = [
                    "name" => "编辑",
                    "type" => "顶部页卡",
                    "title" => "编辑用户",
                    "url" => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
                    'style' => 'li-btn-blue-bg',
                ];
                switch ($info['state']) {
                    case '停用':
                        $firState = '启用';
                        $titleOne = '启用';
                        break;
                    default:
                        $firState = '停用';
                        $titleOne = '停用';
                        break;
                }
                //按钮
                $button[] = [
                    "name" => $titleOne,
                    "type" => "点击事件",
                    "cla" => $this->get('cla'),
                    "fun" => "layer('" . $this->get('cla') . "','stateSwitch',{type:'{$firState}',id:'{$info['id']}'})",
                ];

            }
            if ($this->power(self::page,'del')){
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            $hall = query('dining_hall',"id = '$info[hallId]'");
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "基本信息" => array(
                    array(
                        "食堂名称" => $hall['name'],
                        "菜谱名称" => $info['name'],
                        "起止日期" => $info['startDate'].'至'.$info['endDate'],
                    ),
                    array(
                        "创建人" => self::findStaff($info['stid']),
                        "创建时间" => $info['time'],
                        "状态" => $info['state'],
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => '明细',
                'html' => $this->orderMenu($info['id'],$info['startDate'],true),
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }
    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page. 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] !='停用'){
                    $warn = "删除失败：不是停用状态";
                }else{
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    delete(array("table" => 'dining_week_menu_date', "where" => " orderId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
}
